#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'wshu'
__version__ = '1.0'
"""
    ***********************************
    *  @filename : audits.py
    *  @Author : wshu
    *  @CodeDate : 2020/4/22 11:33
    *  @Software : PyCharm
    ***********************************
"""
from core import BaseHandlers
import tornado.escape
from datetime import datetime, timedelta
from db.mysql import Task, Site
from db.mysql import Strategy, KwBody, AiBody
from db.mysql import TextResultStor, ImageResultStor
from core.comm.http.JsonResponse import Jsonify, JsonForm
from core.comm.utils.timezone import now as timezone
from Ui.HFmSetting.utils.functional import paging
from sqlalchemy.orm import load_only, aliased    # load_only：制定列查询(不适用Table对象，仅适用于类)
from sqlalchemy import func, and_, or_, desc, cast, Numeric, DATE, distinct, extract
from sqlalchemy.sql import exists

class AuditViewHandler(BaseHandlers):
    """
    站点审查管理
    """
    error_msg = ''

    def get(self, *args, **kwargs):
        task_list = self.db.query(Task).all()
        strategy_list = self.db.query(Strategy).all()
        self.render('audit/audit_list.html', error_msg=self.error_msg,
                    task_list=task_list,
                    strategy_list=strategy_list)


class AuditListHandler(BaseHandlers):
    """
    站点审查列表
    """
    error_msg = ''

    @staticmethod
    def get_count(Q):
        count_query = Q.statement.with_only_columns([func.count()]).order_by(None)
        count = Q.session.execute(count_query).scalar()
        return count

    def post(self, *args, **kwargs):
        """
        站点审查展示
        """
        page = self.get_argument('page', None)
        rows = self.get_argument('limit', None)
        taskname = self.get_argument('taskname', None)
        types = self.get_argument('status', None)

        if not taskname:
            taskname = ''
        if not types:
            types = ''

        # 分页查询 p: 页 r: 条
        p, r = paging(page, rows)

        # 文本和图片的信息分别存储在两站表中，所以需要在渲染审查页面时候统计两张表的数据
        # FIXME: 之前结果都是存储在一张表进行维护，因文本和图片有差异化，所以分表存储
        #  两张表中相同字段较多，图片表新增： 本地存储地址、分值 以及关联的爬虫存储结果表
        text_res_data = self.db.query(TextResultStor.idents_mode, TextResultStor.idents_type, TextResultStor.last_time)

        img_res_data = self.db.query(ImageResultStor.idents_mode.label('idents_mode'),
                                     ImageResultStor.idents_type.label('idents_type'),
                                     ImageResultStor.last_time.label('last_time'),)
        union_result_obj = text_res_data.union_all(img_res_data)
        task_for_image_list = union_result_obj.order_by(desc(TextResultStor.last_time)).slice(p, r).all()
        print(task_for_image_list)

        laydata = []
        tempDict = {}
        tempDict['site_id'] = '01'
        tempDict['taskname'] = '福建省'
        tempDict['sitename'] = 'http:fujian.com'
        tempDict['mode'] = '关键词'
        tempDict['type'] = '涉黄'
        tempDict['keywords'] = '苍井空，小泽玛利亚，黄色，渣渣'
        tempDict['number'] = 10
        tempDict['start_at'] = '2020-04-26 12:04:32'
        laydata.append(tempDict)
        # print(">>>: ", laydata)
        # 以JSON形式返回数据
        json_data = Jsonify(
            code=0,
            msg="审查列表",
            count=1,
            data=laydata).json()
        self.write(json_data)

class NumListHandler(BaseHandlers):
    """
    网站审查数量详情展示
    扫描地址下涉及的每个违规详情
    例如：任务: 福建省  站点: http:www.fujian.com  数量：10 ——详情：http:www.fujian.com/page/1 、http:www.fujian.com/page/2
    """
    error_msg = ''

    def get(self, site_id):
        print("get......站点ID: ", site_id)
        self.render('audit/audit_details.html', error_msg=self.error_msg, site_id=site_id)

    def post(self, site_id):
        """
        审查二级展示页面-违规站点详情
        """
        # 获取站点ID，根据站点ID来查询相应的结果
        site_id = self.get_argument('site_id', None)
        print('post.....站点ID: ', site_id)
        laydata = []
        tempDict = {}
        tempDict['site_id'] = '01'
        tempDict['addr'] = 'http://fujian.com/page/1/1213232.html'
        tempDict['keywords'] = '苍井空'
        tempDict['last_time'] = '2020-04-26 12:04:32'
        laydata.append(tempDict)
        # print(">>>: ", laydata)
        # 以JSON形式返回数据
        json_data = Jsonify(
            code=0,
            msg="违规站点详情",
            count=1,
            data=laydata).json()
        self.write(json_data)


class AuditInfoHandler(BaseHandlers):
    """
    违规信息
    """
    error_msg = ''

    def get(self, site_id):
        self.render('audit/audit_info.html', error_msg=self.error_msg)

    def post(self, site_id):
        self.write('ok')